package dbops

import (
	"log"

	_ "github.com/go-sql-driver/mysql" // _ 是用来调用初始化msyql初始化方法init()的
	utils "github.com/lierdan/golangweb/internal/utils"

	"github.com/lierdan/golangweb/internal/defs"
)

// 增加
func AddUser(user *defs.User) error {
	name := user.Name
	password := user.Password

	uuid, _ := utils.NewUUIDSimplicity()
	password = utils.StringMD5(password + uuid)

	// 插入数据
	stmt, err := ConnDb.Prepare("INSERT INTO `user`(`user`,`password`,`salt`) VALUE(?, ?, ?)")
	defer stmt.Close()

	if err != nil {
		log.Println(err.Error())
		return err
	}

	_, err = stmt.Exec(name, password, uuid)
	log.Println("插入数据成功！")
	return err
}

// 单查找
func SelectUser(user *defs.User) error {
	stmt, err := ConnDb.Prepare("SELECT user,password FROM `user` WHERE `user`= ?")
	defer stmt.Close()
	if err != nil {
		log.Println(err.Error())
		return err
	}
	var pwd1 string
	var pwd2 string

	err = stmt.QueryRow(user.Name).Scan(&pwd1, &pwd2)
	log.Println("pwd:", pwd1, pwd2)
	log.Println("查询单条数据成功！")
	return err
}
